package com.lll.nettywebsocket.redis;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.lll.nettywebsocket.common.Constants;
import com.lll.nettywebsocket.repository.WebsocketSessionRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.yeauty.pojo.Session;

import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class RedisMessageListener implements MessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WebsocketSessionRepository websocketSessionRepository;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取消息
        byte[] messageBody = message.getBody();
        // 使用值序列化器转换
        Object msg = redisTemplate.getValueSerializer().deserialize(messageBody);
        // 获取监听的频道
        byte[] channelByte = message.getChannel();
        // 使用字符串序列化器转换
        Object channel = redisTemplate.getStringSerializer().deserialize(channelByte);
        // 渠道名称转换
        String patternStr = new String(pattern);
        log.info(patternStr);
        log.info("---频道---: " + channel);
        log.info("---消息内容---: " + msg);
        String msgStr = (String) msg;
        if (StrUtil.isBlank(msgStr)) {
            log.error("msgStr is blank");
            return;
        }
        com.lll.nettywebsocket.pojo.Message socketMessage = JSONObject.parseObject(msg.toString(), com.lll.nettywebsocket.pojo.Message.class);
        if (Objects.isNull(socketMessage)) {
            log.error("socketMessage is null");
            return;
        }
        if ("all".equals(socketMessage.getTo())) {
            // 群发广播
            List<Session> sessions = websocketSessionRepository.findAllSessions();
            if (CollUtil.isNotEmpty(sessions)) {
                // 连接在了本台服务器
                for (Session s : sessions) {
                    if (!s.getAttribute(Constants.CID).equals(socketMessage.getCid())) { // 不要再发给自己了
                        s.sendText(socketMessage.getContent());
                    }
                }
            }
            //            else {
            //                // 连接到其他服务器，通知其他节点处理
            //                log.info("broadcast .....");
            //                redisTemplate.convertAndSend(Constants.REDIS_CHANNEL_NAME, msg);
            //            }

        } else {
            List<Session> sessions = websocketSessionRepository.findSession(socketMessage.getTo());
            if (CollUtil.isNotEmpty(sessions)) {
                // 连接在了本台服务器
                for (Session s : sessions) {
                    if (!s.getAttribute(Constants.CID).equals(socketMessage.getCid())) { // 不要再发给自己了
                        s.sendText(socketMessage.getContent());
                    }
                }
            }
            //            else {
            //                // 连接到其他服务器，通知其他节点处理
            //                log.info("broadcast .....");
            //                redisTemplate.convertAndSend(Constants.REDIS_CHANNEL_NAME, msg);
            //            }
        }
    }
}